const Alumni = require('../models/alumni');
const pool = require('../config/database');

exports.getAlumniList = async (req, res) => {
  try {
    // 验证分页参数
    let { keyword, industry, page = 1, pageSize = 20 } = req.query;
    page = Math.max(1, parseInt(page));
    pageSize = Math.min(Math.max(10, parseInt(pageSize)), 100);
    
    console.log('获取校友列表参数:', { keyword, industry, page, pageSize });

    // 使用模型中的方法获取校友列表
    const [alumni, total] = await Promise.all([
      Alumni.getAllAlumni({ keyword, industry, page, pageSize })
        .catch(err => {
          console.error('获取校友列表失败:', err);
          throw new Error('获取校友列表失败');
        }),
      Alumni.countAllAlumni({ keyword, industry })
        .catch(err => {
          console.error('统计校友总数失败:', err);
          throw new Error('统计校友总数失败');
        })
    ]);
    
    // 解析contact_info字段
    const parsedAlumni = alumni.map(item => {
      let contactInfo = {};
      try {
        contactInfo = typeof item.contact_info === 'string' 
          ? JSON.parse(item.contact_info || '{}')
          : item.contact_info || {};
      } catch (error) {
        console.error('解析contact_info失败:', error);
        contactInfo = {};
      }
      return {
        ...item,
        email: contactInfo.email || '',
        phone: contactInfo.phone || '',
        industry: contactInfo.industry || ''
      };
    });

    console.log('查询结果:', { alumniCount: parsedAlumni.length, total });

    res.json({
      success: true,
      alumni: parsedAlumni,
      pagination: {
        page,
        pageSize,
        total
      }
    });

  } catch (error) {
    console.error('获取校友列表失败:', error.stack || error);
    res.status(500).json({ 
      success: false,
      message: '获取校友列表失败，请稍后重试',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
};

// 获取单个校友详情
exports.getAlumniDetail = async (req, res) => {
    try {
    const alumni = await Alumni.getById(req.params.id);
    if (!alumni) {
        return res.status(404).json({ 
          success: false,
          message: '校友信息未找到'
        });
      }

      // 处理contact_info
      let contactInfo = {};
      try {
        contactInfo = typeof alumni.contact_info === 'string'
          ? JSON.parse(alumni.contact_info || '{}')
          : alumni.contact_info || {};
      } catch (error) {
        console.error('解析contact_info失败:', error);
        contactInfo = {};
      }

      const response = {
        success: true,
        data: {
          id: alumni.id,
          name: alumni.name,
          company: alumni.company,
          position: alumni.position,
          email: alumni.email || contactInfo.email || '',
          phone: alumni.phone || contactInfo.phone || '',
          industry: alumni.industry || contactInfo.industry || '',
          visibility: alumni.visibility,
          hasOpenings: alumni.hasOpenings,
          createdAt: alumni.created_at,
          updatedAt: alumni.updated_at
        }
      };

      res.json(response);
    } catch (error) {
      console.error('获取校友详情失败:', error);
      res.status(500).json({
        success: false,
        message: '获取校友详情失败',
        error: process.env.NODE_ENV === 'development' ? error.message : undefined
      });
    }
};

// 更新校友信息
exports.updateAlumni = (req, res) => {
  const { name, company, position, contactInfo, visibility,hasOpenings } = req.body;
  
  Alumni.update(req.params.id, {
    name,
    company,
    position,
    contactInfo,
    visibility,
    hasOpenings
  }, (error, success) => {
    if (error) {
      return res.status(400).json({ message: error.message });
    }
    
    if (!success) {
      return res.status(404).json({ message: 'Alumni not found' });
    }
    res.json({ message: 'Alumni updated successfully' });
  });
};

// 标记公司开放岗位
exports.markCompanyJobs = (req, res) => {
  const { companyId } = req.params;
  
  pool.query(
    'UPDATE alumni SET has_openings = 1 WHERE company = ?',
    [companyId],
    (error, result) => {
      if (error) {
        return res.status(500).json({ message: error.message });
      }
      
      res.json({ 
        message: 'Company jobs marked successfully',
        affectedRows: result.affectedRows 
      });
    }
  );
};

// 请求联系方式
exports.requestContact = async (req, res) => {
  const startTime = Date.now();
  const { id } = req.params;
  const { requesterId, message } = req.body;

  console.log(`[${new Date().toISOString()}] 开始处理请求联系方式请求`);

  // 设置请求超时
  req.setTimeout(5000, () => {
    console.error(`[${new Date().toISOString()}] 请求超时`);
    return res.status(504).json({
      success: false,
      message: '请求超时'
    });
  });

  if (!requesterId || !message) {
    console.error(`[${new Date().toISOString()}] 缺少必要参数`);
    return res.status(400).json({ 
      success: false,
      message: '缺少必要参数' 
    });
  }

  try {
    // 检查连接池状态
    if (!pool || pool._closed) {
      console.error(`[${new Date().toISOString()}] 数据库连接池不可用`);
      return res.status(500).json({
        success: false,
        message: '数据库连接池不可用'
      });
    }

    // 使用Promise.all并行执行查询
    const [userResult, alumniResult] = await Promise.all([
      pool.execute('SELECT id FROM users WHERE id = ?', [requesterId]),
      pool.execute('SELECT id FROM alumni WHERE id = ?', [id])
    ]);

    // 验证用户和校友是否存在
    if (!userResult[0].length || !alumniResult[0].length) {
      console.error(`[${new Date().toISOString()}] 用户或校友不存在`);
      return res.status(404).json({ 
        success: false,
        message: '用户或校友不存在' 
      });
    }

    // 插入消息
    const [insertResult] = await pool.execute(
      `INSERT INTO messages 
        (sender_id, receiver_id, content, status, created_at) 
        VALUES (?, ?, ?, ?, NOW())`,
      [requesterId, id, message, 'unread']
    );

    const duration = Date.now() - startTime;
    console.log(`[${new Date().toISOString()}] 请求处理完成，耗时 ${duration}ms`);

    res.json({
      success: true,
      message: '消息已发送',
      messageId: insertResult.insertId
    });

  } catch (error) {
    const duration = Date.now() - startTime;
    console.error(`[${new Date().toISOString()}] 消息发送失败，耗时 ${duration}ms`, error);
    return res.status(500).json({ 
      success: false,
      message: '消息发送失败' 
    });
  }
};
